import { api, getCurrentUser } from './api.js';

document.addEventListener('DOMContentLoaded', async () => {
    // 检查登录状态
    const user = await getCurrentUser();
    if (!user) {
        window.location.href = 'index.html';
        return;
    }

    // 初始化订单页面
    initOrderPage();
    
    // 绑定事件
    bindEvents();
});

let dishes = [];
let categories = [];
let cartItems = [];

async function initOrderPage() {
    try {
        // 加载菜品分类
        const categoriesResponse = await api.get('/menu/categories');
        categories = categoriesResponse;
        renderCategories();
        
        // 加载所有菜品
        const dishesResponse = await api.get('/menu/dishes');
        dishes = dishesResponse;
        renderDishes();
        
        // 加载购物车（如果有本地存储的）
        loadCartFromStorage();
    } catch (error) {
        console.error('初始化订单页面失败:', error);
        alert('加载菜单失败，请刷新重试');
    }
}

function renderCategories() {
    const container = document.querySelector('.dish-categories');
    
    // 清空现有分类
    container.innerHTML = '';
    
    // 添加"全部"分类
    const allBtn = document.createElement('button');
    allBtn.className = 'category-btn active';
    allBtn.textContent = '全部';
    allBtn.setAttribute('data-category', 'all');
    container.appendChild(allBtn);
    
    // 添加其他分类
    categories.forEach(category => {
        const btn = document.createElement('button');
        btn.className = 'category-btn';
        btn.textContent = category.name;
        btn.setAttribute('data-category', category.id);
        container.appendChild(btn);
    });
}

function renderDishes(categoryId = 'all') {
    const container = document.querySelector('.dish-list');
    
    // 清空现有菜品
    container.innerHTML = '';
    
    // 过滤菜品
    const filteredDishes = categoryId === 'all' 
        ? dishes 
        : dishes.filter(dish => dish.category_id == categoryId);
    
    // 渲染菜品卡片
    filteredDishes.forEach(dish => {
        const card = document.createElement('div');
        card.className = 'dish-card';
        
        // 检查是否已在购物车中
        const inCart = cartItems.some(item => item.dish_id === dish.id);
        const cartItem = inCart ? cartItems.find(item => item.dish_id === dish.id) : null;
        
        card.innerHTML = `
            <div class="dish-image" style="background-image: url('${dish.image_url || 'assets/images/default-dish.jpg'}')"></div>
            <div class="dish-info">
                <h4 class="dish-name">${dish.name}</h4>
                <div class="dish-price">¥${dish.price.toFixed(2)}</div>
                <div class="dish-stock">库存: ${dish.stock}</div>
                <button class="add-to-cart" data-dish-id="${dish.id}" ${dish.stock <= 0 ? 'disabled' : ''}>
                    ${inCart ? '已添加' : '加入购物车'}
                </button>
            </div>
        `;
        
        container.appendChild(card);
    });
}

function bindEvents() {
    // 分类切换
    document.querySelector('.dish-categories').addEventListener('click', (e) => {
        if (e.target.classList.contains('category-btn')) {
            // 更新活动按钮
            document.querySelectorAll('.category-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            e.target.classList.add('active');
            
            // 渲染对应分类的菜品
            const categoryId = e.target.getAttribute('data-category');
            renderDishes(categoryId);
        }
    });
    
    // 添加到购物车
    document.querySelector('.dish-list').addEventListener('click', (e) => {
        if (e.target.classList.contains('add-to-cart')) {
            const dishId = parseInt(e.target.getAttribute('data-dish-id'));
            addToCart(dishId);
        }
    });
    
    // 提交订单
    document.getElementById('delivery-form').addEventListener('submit', submitOrder);
    
    // 退出登录
    document.getElementById('logout-btn').addEventListener('click', logout);
}

function addToCart(dishId) {
    const dish = dishes.find(d => d.id === dishId);
    if (!dish) return;
    
    // 检查是否已在购物车中
    const existingItem = cartItems.find(item => item.dish_id === dishId);
    
    if (existingItem) {
        // 如果已在购物车中，增加数量
        if (existingItem.quantity < dish.stock) {
            existingItem.quantity += 1;
        } else {
            alert('已达到最大库存数量');
            return;
        }
    } else {
        // 如果不在购物车中，添加新项
        cartItems.push({
            dish_id: dishId,
            name: dish.name,
            price: dish.price,
            quantity: 1
        });
    }
    
    // 更新UI
    updateCartUI();
    renderDishes(document.querySelector('.category-btn.active').getAttribute('data-category'));
    
    // 保存到本地存储
    saveCartToStorage();
}

function updateCartUI() {
    const tbody = document.getElementById('selected-items-body');
    const totalAmountElement = document.getElementById('total-amount');
    
    // 清空现有行
    tbody.innerHTML = '';
    
    let totalAmount = 0;
    
    // 添加购物车项
    cartItems.forEach((item, index) => {
        const subtotal = item.price * item.quantity;
        totalAmount += subtotal;
        
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${item.name}</td>
            <td>¥${item.price.toFixed(2)}</td>
            <td>
                <div class="quantity-control">
                    <button class="quantity-btn minus" data-index="${index}">-</button>
                    <span>${item.quantity}</span>
                    <button class="quantity-btn plus" data-index="${index}">+</button>
                </div>
            </td>
            <td>¥${subtotal.toFixed(2)}</td>
            <td><button class="remove-btn" data-index="${index}">删除</button></td>
        `;
        tbody.appendChild(row);
    });
    
    // 更新总金额
    totalAmountElement.textContent = `¥${totalAmount.toFixed(2)}`;
    
    // 绑定数量控制按钮事件
    document.querySelectorAll('.quantity-btn').forEach(btn => {
        btn.addEventListener('click', handleQuantityChange);
    });
    
    // 绑定删除按钮事件
    document.querySelectorAll('.remove-btn').forEach(btn => {
        btn.addEventListener('click', handleRemoveItem);
    });
}

function handleQuantityChange(e) {
    const index = parseInt(e.target.getAttribute('data-index'));
    const item = cartItems[index];
    const dish = dishes.find(d => d.id === item.dish_id);
    
    if (e.target.classList.contains('minus')) {
        // 减少数量
        if (item.quantity > 1) {
            item.quantity -= 1;
        } else {
            // 如果数量为1，点击减号则移除该项
            cartItems.splice(index, 1);
        }
    } else if (e.target.classList.contains('plus')) {
        // 增加数量
        if (item.quantity < dish.stock) {
            item.quantity += 1;
        } else {
            alert('已达到最大库存数量');
        }
    }
    
    // 更新UI
    updateCartUI();
    renderDishes(document.querySelector('.category-btn.active').getAttribute('data-category'));
    saveCartToStorage();
}

function handleRemoveItem(e) {
    const index = parseInt(e.target.getAttribute('data-index'));
    cartItems.splice(index, 1);
    
    // 更新UI
    updateCartUI();
    renderDishes(document.querySelector('.category-btn.active').getAttribute('data-category'));
    saveCartToStorage();
}

async function submitOrder(e) {
    e.preventDefault();
    
    // 验证购物车不为空
    if (cartItems.length === 0) {
        alert('请至少选择一件商品');
        return;
    }
    
    // 获取配送信息
    const deliveryAddress = document.getElementById('delivery-address').value;
    const contactPhone = document.getElementById('contact-phone').value;
    const specialNotes = document.getElementById('special-notes').value;
    
    // 准备订单数据
    const orderData = {
        items: cartItems.map(item => ({
            dish_id: item.dish_id,
            quantity: item.quantity
        })),
        delivery_address: deliveryAddress,
        contact_phone: contactPhone,
        special_notes: specialNotes
    };
    
    try {
        // 提交订单
        const response = await api.post('/orders', orderData);
        
        // 清空购物车
        cartItems = [];
        updateCartUI();
        saveCartToStorage();
        
        // 跳转到订单详情页
        alert('订单创建成功！');
        window.location.href = `orders.html`;
    } catch (error) {
        console.error('提交订单失败:', error);
        alert(`提交订单失败: ${error.message}`);
    }
}

function saveCartToStorage() {
    localStorage.setItem('cart', JSON.stringify(cartItems));
}

function loadCartFromStorage() {
    const savedCart = localStorage.getItem('cart');
    if (savedCart) {
        cartItems = JSON.parse(savedCart);
        updateCartUI();
    }
}

async function logout() {
    try {
        await api.post('/auth/logout');
        localStorage.removeItem('cart');
        window.location.href = 'index.html';
    } catch (error) {
        console.error('退出登录失败:', error);
    }
}